﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Data;
using Newtonsoft.Json.Linq;

namespace JsonEditor
{
    public class JObjectSortPropertyConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            List<JProperty> properties = null;
            JObject jObject = value as JObject;

            if (jObject != null)
            {
                properties = new List<JProperty>();

                jObject.Properties().ToList().ForEach(p =>
                {
                    p.Remove();
                    properties.Add(p);
                });

                properties.OrderBy(p => p.Name).ToList().ForEach(p => jObject.Add(p));
            }

            return value;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}
